package net.wxxr.http.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.GZIPInputStream;


public class CodeUtil {

	public static String toMD5(String src) throws NoSuchAlgorithmException {
		MessageDigest algorithm = MessageDigest.getInstance("MD5");
		algorithm.reset();
		algorithm.update(src.getBytes());
		return toHexString(algorithm.digest(), "");
	}

	private static String toHexString(byte[] bytes, String separator) {
		StringBuilder hexString = new StringBuilder();
		for (byte b : bytes) {
			hexString.append(Integer.toHexString(0xFF & b)).append(separator);
		}
		return hexString.toString();
	}

	public static String urlEncode(String str) throws UnsupportedEncodingException {
		return URLEncoder.encode(str, Constants.UTF8).replaceAll("\\+", "%20").replaceAll("%7E", "~").replaceAll("\\*", "%2A");
	}


    public static byte[] gzipDecoder(byte[] src) throws IOException {
		ByteArrayInputStream is = new ByteArrayInputStream(src);
		GZIPInputStream gis = null;
		byte[] desbyte = null;

		try {
			gis = new GZIPInputStream(is);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int byteRead = 0;
			byte[] tempBytes = new byte[Constants.READ_BUFFER];

			while ((byteRead = gis.read(tempBytes)) != -1) {
				baos.write(tempBytes, 0, byteRead);
			}
			desbyte = baos.toByteArray();

		} finally {
			try {
				is.close();
				if (gis != null) {
					gis.close();
				}
			} catch (IOException e) {
				throw e;
			}
		}

		return desbyte;
	}
}
